package cn.wenhaha.common.db.bean;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.wenhaha.common.bean.entity.TimeEntity;
import cn.wenhaha.common.db.bean.model.BaseSysSyncReport;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报表
 * </p>
 *
 * @Author: Wyndem
 * @DateTime: 2022-12-18 17:27
 */
@Component
public class SysSyncReport extends BaseSysSyncReport<SysSyncReport> {


    public Map<String, Object> basicCount() {
        Date date = DateUtil.beginOfDay(new Date()).toJdkDate();
        return template("SysSyncReport.basicCount", Kv.by("startDate", DateUtil.formatDate(date))).findFirst()._getAttrs();

    }


    public List<SysSyncReport> reportWeek(Integer mappingId) {
        Date date = new Date();
        Date startDate = DateUtil.beginOfWeek(date).toJdkDate();
        Date endDate = DateUtil.endOfWeek(date).toJdkDate();
        return template("SysSyncReport.reportWeek", Kv.by("id", mappingId)
                .set("startDate", DateUtil.formatDate(startDate))
                .set("endDate", DateUtil.formatDate(endDate))
        ).find();
    }


    public SysSyncReport queryByMapping(Integer mapping, String nameData, String upload, TimeEntity timeEntity) {

        return findFirst("SELECT * FROM sys_sync_report WHERE " +
                        "mapping_id = ? AND name_data =  ? AND name_upload = ?  AND type = ? AND start_date = ? AND end_date = ?" +
                        "LIMIT 1",
                mapping, nameData, upload, timeEntity.getCode(), timeEntity.startDate(), timeEntity.endDate());
    }


    public List<SysSyncReport> state() {
        Date date = DateUtil.beginOfDay(new Date()).toJdkDate();

        return template("SysSyncReport.state", Kv.by("date", DateUtil.formatDate(date))).find();
    }


    /**
     * <p>
     * 删除 小于当前时间的数据 ,已经子集
     * </p>
     *
     * @Author: Wyndem
     * @DateTime: 2023-01-27 12:37
     */
    public int deleteByLTDate(Date date,Integer type) {
        String str = DateUtil.formatDate(date);
        return Db.update("DELETE FROM sys_sync_report  WHERE start_date < ? AND type <= ?" , str,type);
    }


    public void saveOrUpdate() {
        if (StrUtil.isEmpty(getId())) {
            setId(IdUtil.fastSimpleUUID());
            save();
        } else {
            update();
        }
    }
}

